package initplugs

import (
	"github.com/go-kratos/aegis/circuitbreaker"
	"github.com/go-kratos/aegis/circuitbreaker/sre"
	"github.com/go-kratos/aegis/ratelimit"
	"github.com/go-kratos/aegis/ratelimit/bbr"
)

var (
	RateLimiter    *fginRateLimiter
	CircuitBreaker *fginCircuitBreaker
)

const (
	RateCode      = 429          // 限流状态码
	RateErrMsg    = "网络繁忙,请稍后再试" // 限流提醒
	CircuitCode   = 503          // 熔断状态码
	CircuitErrMsg = "服务异常,请稍后再试" // 熔断状态提醒
)

// 限流器结构
type fginRateLimiter struct {
	Limiter ratelimit.Limiter
}

func (l *fginRateLimiter) Allow() error {
	if fginConfig.RateLimiter {
		done, err := l.Limiter.Allow()
		if err != nil {
			return err
		}
		// 未进入限流，执行请求记录+1
		done(ratelimit.DoneInfo{})
		return nil
	}
	return nil
}

// 限流器
func fginRateLimiterInit() {
	RateLimiter = &fginRateLimiter{}
	if fginConfig.RateLimiter {
		RateLimiter.Limiter = bbr.NewLimiter()
		LogSuger.Info("限流器启动成功")
	}
}

// 熔断器结构
type fginCircuitBreaker struct {
	Breaker circuitbreaker.CircuitBreaker
}

func (b *fginCircuitBreaker) Allow() error {
	if fginConfig.CircuitBreaker {
		return b.Breaker.Allow()
	}
	return nil
}

func (b *fginCircuitBreaker) MarkSuccess() {
	if fginConfig.CircuitBreaker {
		b.Breaker.MarkSuccess()
	}
}

func (b *fginCircuitBreaker) MarkFailed() {
	if fginConfig.CircuitBreaker {
		b.Breaker.MarkFailed()
	}
}

// 熔断器
func fginCircuitBreakerInit() {
	CircuitBreaker = &fginCircuitBreaker{}
	if fginConfig.CircuitBreaker {
		CircuitBreaker.Breaker = sre.NewBreaker()
		LogSuger.Info("熔断器启动成功")
	}
}

// 神盾初始化
func initAegis() {
	fginRateLimiterInit()
	fginCircuitBreakerInit()
}
